package chisel3

import chisel3.internal.requireIsChiselType // Fix ambiguous import
import chisel3.internal.{throwException, Builder}
import chisel3.experimental.SourceInfo
import chisel3.properties.{Class, Property}

object IO {

  def apply[T <: Data](iodef: => T)(implicit sourceInfo: SourceInfo): T = {
    val module = Module.currentModule.get // Impossible to fail
    if (!module.isIOCreationAllowed)
      Builder.error(
        s"This module cannot have IOs instantiated after disallowing IOs: ${module._whereIOCreationIsDisallowed
          .map(_.makeMessage { s: String => s })
          .mkString(",")}"
      )
    require(!module.isClosed, "Can't add more ports after module close")
    val prevId = Builder.idGen.value
    val data = iodef // evaluate once (passed by name)
    requireIsChiselType(data, "io type")

    // Fail if the module is a Class, and the type is Data.
    module match {
      case _: Class => {
        data match {
          case _: Property[_] => ()
          case _ => Builder.error(s"Class ports must be Property type, but found ${data._localErrorContext}.")
        }
      }
      case _ => ()
    }

    val iodefClone =
      if (!data.mustClone(prevId)) data
      else
        try {
          data.cloneTypeFull
        } catch {
          // For now this is going to be just a deprecation so we don't suddenly break everyone's code
          case e: AutoClonetypeException =>
            Builder.deprecated(e.getMessage, Some(s"${data.getClass}"))
            data
        }
    module.bindIoInPlace(iodefClone)
    iodefClone
  }
}
